using System;
using System.Linq;
using System.Xml.Linq;
using FluentlyXml.Core.Serialization;
using FluentlyXml.Core.Utility;

namespace FluentlyXml.Core.BuiltInSerializers
{
	internal class ArraySerializer : ITypeSerializer
	{
		public bool CanSerialize(Type type)
		{
			return type.IsArray;
		}

		public XElement Serialize(Type arrayType, object obj, ISerializationContext context)
		{
			var elementType = arrayType.GetElementType();

			var element = new XElement("ArrayOf" + elementType.Name);

			var subElements = from object i in (Array)obj
							  select context.Serialize(elementType, i);

			subElements.ForEach(e => element.Add((object) e));

			return element;
		}
	}
}